package StudyCode.summary.myfile;

import java.io.ByteArrayOutputStream;
import java.util.Arrays;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ConvertBinaryStringToByteArray {

	public static void main(String[] args) {
		String str = "0101010101011100";
		System.out.println(str + "转为字节数组:");
		System.out.println(Arrays.toString(binaryStringToBytes(str)));
	}

	private static byte[] binaryStringToBytes(String str) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int curByte = 0;

		int i, bc = 0;
		for (i = 0; i < str.length(); i++) {
			int bit;
			char charAt = str.charAt(i);
			if (charAt == '1')
				bit = 1;
			else if (charAt == '0')
				bit = 0;
			else
				continue;

			curByte |= bit << (7 - bc % 8);
			if (bc % 8 == 7) {
				baos.write(curByte);
				curByte = 0;
			}
			bc++;
		}
		if (bc % 8 != 0)
			baos.write(curByte);

		return baos.toByteArray();
	}
}
